package com.candy.shoporder.controller;

import com.candy.entity.Order;
import com.candy.shoporder.service.OrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import java.util.List;

@RestController
@RefreshScope
@RequestMapping("/order")
public class OrderController {
    @Autowired
    OrderService orderService;
    @Autowired
    private RestTemplate restTemplate;
    @Autowired
    private DiscoveryClient discoveryClient;
    @Value("${author}")
    String author;

    @RequestMapping("/addOrder")
    public String addOrder() {
        Order order=new Order();
        order.setUserId(2);
        order.setUsername("candy");
        order.setProductId(1);
        order.setProductName("Java从入门到精通");
        order.setAmount(61.5);
        order.setNumber(1);
        order.setPrice(61.5);
        orderService.addOrder(order);
//        调用库存的服务，进行商品库存的更新（方式一）
//        String productMessage=restTemplate.getForObject("http://localhost:8082/editProductStock",String.class);
//       获取服务的示例（方式二）
//        List<ServiceInstance> instances= discoveryClient.getInstances("shop-product");
//        ServiceInstance instance= instances.get(0);
//        获取实例的host
//        String productHost=instance.getHost();
//        获取实例的端口
//        int productPort=instance.getPort();
//        调用product服务中库存修正的方法
//        String productMessage=restTemplate.getForObject("http://"+productHost+":"+productPort+"/editProductStock",String.class);
//      服务调用方式三
        String productMessage=restTemplate.getForObject("http://shop-product/product/editProductStock",String.class);

        return "订单添加成功"+productMessage+",作者："+author;
    }

}
